﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using WeatherHistory.Data.Repositories.Interfaces;
using WeatherHistory.Shared.Exceptions;

namespace WeatherHistory.Api.CommandsQueries.Commands.Regions.DetachWeather;

public class DetachWeatherRegionsCommandHandler : IRequestHandler<DetachWeatherRegionsCommandRequest, DetachWeatherRegionsCommandResponse>
{
    private readonly IMapper _mapper;
    private readonly IRegionRepository _regionRepository;

    public DetachWeatherRegionsCommandHandler(IMapper mapper, IRegionRepository regionRepository)
    {
        _mapper = mapper;
        _regionRepository = regionRepository;
    }

    public async Task<DetachWeatherRegionsCommandResponse> Handle(DetachWeatherRegionsCommandRequest request, CancellationToken cancellationToken)
    {
        var region = await _regionRepository
            .AsQueryable()
            .Include(x => x.Weathers).ThenInclude(x => x.Forecasts)
            .Include(x => x.ParentRegion)
            .FirstOrDefaultAsync(x => x.Id == request.RegionId, cancellationToken);
        if (region == null) throw new NotFoundException($"Регион с id '{request.RegionId}' не найдена");

        region.Weathers = region.Weathers.Where(x => x.Id != request.WeatherId).ToList();
        await _regionRepository.UpdateAsync(region, cancellationToken);

        return _mapper.Map<DetachWeatherRegionsCommandResponse>(region);
    }
}